package patterns.observePattern;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MobileServerData {
	private Float netStreamPrice = 0f;
	private Float voiceCommunicationPrice = 0f;
	private List<ServiceUser> serviceUsers = new ArrayList<>();
	boolean couldPush = false;
	private List<Observed> observeds = new ArrayList<>();
	private String deleteObseredLock = "deleteObseredLock";

	public Float getNetStreamPrice() {
		return netStreamPrice;
	}

	public void setNetStreamPrice(Float netStreamPrice) {
		if (this.netStreamPrice != netStreamPrice) {
			this.netStreamPrice = netStreamPrice;
			// setCouldPush(true);
			pushInfo();
		}
	}

	public Float getVoiceCommunicationPrice() {
		return voiceCommunicationPrice;
	}

	public void setVoiceCommunicationPrice(Float voiceCommunicationPrice) {
		if (this.voiceCommunicationPrice != voiceCommunicationPrice) {
			this.voiceCommunicationPrice = voiceCommunicationPrice;
			// setCouldPush(true);
			pushInfo();
		}
	}

	private void setCouldPush(boolean couldPush) {
		this.couldPush = couldPush;
	}

	private boolean getCouldPush() {
		return this.couldPush;
	}

	private void pushInfo() {
		// if (getCouldPush() == true) {
		for (ServiceUser serviceUser : serviceUsers) {
			serviceUser.afterNotified();
		}
		// }
	}

	public void addUser(ServiceUser serviceUser) {
		this.serviceUsers.add(serviceUser);
	}

	public void addUserInitiative(ServiceUser serviceUser) throws Exception {
		if (!serviceUsers.contains(serviceUser)) {
			serviceUser.addUserPassive(this);
			serviceUsers.add(serviceUser);
		}
	}

	public void deleteUser(ServiceUser serviceUser) throws Exception {
		if (serviceUsers.contains(serviceUser)) {
			synchronized (this) {
				serviceUsers.remove(serviceUser);
			}
		} else {
			throw new Exception("watcher " + serviceUser.getName() + " is not in current observed server!");
		}
	}

	public void deleteObserved(Observed observed) throws Exception {
		if (observeds.contains(observed)) {
			synchronized (deleteObseredLock) {
				observeds.remove(observed);
			}
		} else {
			throw new Exception("observed " + observed.getName() + " is not bind to current rigester!");
		}
	}

	public final void pushObservedMessage(ObservedMessage message) {
		// TODO Auto-generated method stub
		for (ServiceUser serviceUser : serviceUsers) {
			serviceUser.afterNotifiedOberved(message);
		}
	}

	public void addObseredUser(DiscountInfoPusher discountInfoPusher) {
		// TODO Auto-generated method stub
		if (!observeds.contains(discountInfoPusher)) {
			observeds.add(discountInfoPusher);
		}
	}
}
